<?php

namespace common\repositories\outstock;

use common\entities\myhtsq\ContractApplicationEntity;
use common\entities\outstock\MyscrmOutStockOrderEntity;
use common\entities\outstock\MyscrmOutStockProductEntity;
use common\entities\outstock\MyscrmOutStockStepEntity;
use common\repositories\BaseRepository;
use common\repositories\common\MyscrmContractApplicationRepository;
use common\services\outstock\OutStockFlowService;

/**
 * Created by PhpStorm.
 * User: yuyj
 * Date: 16-12-12
 * Time: 上午11:00
 */
class OutStockOrderRepository extends BaseRepository
{

    /**
     * 未申请列表[我发起的,我代办的]
     * @param       $page
     * @param       $pageSize
     * @param int $action
     * @param       $userId
     * @param array $condition
     * @return array
     */
    public function getOrderList($page, $pageSize, $action = MyscrmOutStockOrderEntity::FLOW_START, $userId, $condition = [])
    {
        if ($page < 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $pageSize;
        $query = MyscrmOutStockOrderEntity::find();
        $query->where([
            'order_status' => 1,
        ]);
        if ($action == MyscrmOutStockOrderEntity::FLOW_START) {
            //交付人员和创建人都要看到
            $query->andFilterWhere(['or',
                    ['deliver_user_id' => $userId],
                    ['request_user_id' => $userId],
                ]
            );
        } else {
            //待办列表
            $query->andFilterWhere(["response_user_id" => $userId, 'flow_status' => [OutStockFlowService::STATUS_YSP, OutStockFlowService::STATUS_SQZ, OutStockFlowService::STATUS_YQR, OutStockFlowService::STATUS_YKT]]);
        }

        $query->andFilterWhere($condition);
        $query->orderBy("created_on desc");

        return [
            'total' => $query->count(1),
            'data'  => $query->limit($pageSize)->offset($offset)->asArray()->all(),
        ];
    }

    /**
     * 已办列表
     * @param       $page
     * @param       $pageSize
     * @param       $userId
     * @param array $condition
     * @return array
     */
    public function getDoneList($page, $pageSize, $userId, $condition = [])
    {
        if ($page < 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $pageSize;

        $query = MyscrmOutStockStepEntity::find()->select("myscrm_out_stock_order.*");
        $query->leftJoin("myscrm_out_stock_order", "myscrm_out_stock_step.order_id=myscrm_out_stock_order.id")
            ->andWhere("myscrm_out_stock_step.action in (10,20,23)")
            ->andFilterWhere(["myscrm_out_stock_step.operate_people_id" => $userId])
            ->andFilterWhere($condition);

        $query->orderBy("myscrm_out_stock_step.created_on desc")->distinct();

        return [
            'total' => $query->count(1),
            'data'  => $query->limit($pageSize)->offset($offset)->asArray()->all(),
        ];
    }

    /**
     * 根据order_code获取单条记录
     * @param $orderCode
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getDetailByCode($orderCode)
    {
        return MyscrmOutStockOrderEntity::find()->where(["order_code" => $orderCode])->asArray()->one();
    }

    /**
     * 获取单据列表
     * @param       $pageSize
     * @param       $pageNo
     * @param array $condition
     * @return array
     */
    public function getList($pageSize, $pageNo, $condition = [])
    {
        $query = MyscrmOutStockOrderEntity::find();
        $query->andFilterWhere($condition);

        return [
            'total' => $query->count(1),
            'data'  => $query->limit($pageSize)->offset($pageSize * $pageNo)->all(),
        ];
    }

    /**
     * 更新字段
     * @param $data
     * @param $orderCode
     * @return int
     */
    public function updateOrderByCode($data, $orderCode)
    {
        return MyscrmOutStockOrderEntity::updateAll($data, ["order_code" => $orderCode]);
    }

    /**
     * 保存单据
     * @param MyscrmOutStockOrderEntity $model
     * @return bool|string
     */
    public function save(MyscrmOutStockOrderEntity $model)
    {
        if ($model->validate() && $model->save()) {
            return $model->id;
        } else {
            $errors = $model->getFirstErrors();

            return self::setAndReturn(__LINE__, implode(';', $errors));
        }
    }

    /**
     * 软删除单据
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        return MyscrmOutStockOrderEntity::updateAll(['order_status' => 0], ['id' => $id]);
    }

    /**
     * @param $contractId     合同ID
     * @param $excludeOrderId 排除单据ID
     * @return mixed
     */
    public function getUsedAuthorizationNumericContractId($contractId, $excludeOrderId)
    {
        $query = MyscrmOutStockOrderEntity::find()
            ->select([
                'myscrm_out_stock_product.application_id',
                'total_used_number' => 'sum(apply_num)',
            ])
            ->leftJoin('myscrm_out_stock_product', 'myscrm_out_stock_product.order_id=myscrm_out_stock_order.id')
            ->where([
                'contract_id'                         => $contractId,
                'myscrm_out_stock_order.order_status' => 1,
            ])
            ->andFilterWhere(['not in', 'myscrm_out_stock_order.id', $excludeOrderId])
            ->groupBy('myscrm_out_stock_product.application_id')
            ->indexBy('application_id');

        return $query->asArray()->all();
    }


    /**
     * @param $id
     * @return MyscrmOutStockOrderEntity
     */
    public function getOrderById($id)
    {
        return MyscrmOutStockOrderEntity::find()
            ->where([
                'id' => $id,
            ])->one();
    }

    /**
     * 获取最新的单据
     * @return MyscrmOutStockOrderEntity
     */
    public function getTodayLatestOrder()
    {
        $query = MyscrmOutStockOrderEntity::find()
            ->where([
                'between', 'created_on', date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59'),
            ])
            ->orderBy('created_on DESC');

        return $query->one();
    }

    /**
     * 获取已使用的授权数量
     * @param $contractApplicationId
     * @param $excludeOrderId
     * @return bool|string
     */
    public function getUsedAuthorizationNumericByContractApplicationId($contractApplicationId, $excludeOrderId)
    {
        return MyscrmOutStockProductEntity::find()
            ->select([
                'total_used_number' => 'sum(apply_num)',
            ])
            ->innerJoin('myscrm_out_stock_order', 'myscrm_out_stock_product.`order_id`=myscrm_out_stock_order.`id`')
            ->where([
                'myscrm_out_stock_product.contract_application_id' => $contractApplicationId,
                'myscrm_out_stock_order.order_status'              => 1,
            ])
            ->andWhere(['<', 'flow_status', 30])
            ->andFilterWhere(['not in', 'order_id', $excludeOrderId])
            ->scalar();
    }
}